<?php

/**
 * manage blocks content
 * @author Tuong Tran <tuong.tran@outlook.com>
 */

//import models
Yii::import('common.models.page.*');
class BlockController extends Controller {
    public $activeMenu = 'page';
    /**
     * read all block and create form
     */
    public function actionIndex() {
        //avaiable blocks
        //check in blocks dir
        $availableBlocks = $this->_getAvaiableBlocks();

        $model = new Block('search');
        if(isset($_GET['Block'])){
            $model->attributes = $_POST['Block'];
        }

        $this->render('index', array(
            'availableBlocks' => $availableBlocks,
            'model' => $model
        ));
    }

    /**
     * create new block
     * @param type $type
     */
    public function actionCreate() {
        if (!isset($_GET['type'])) {
            throw new CHttpException(404, 'Page was not exists');
        }

        $type = $_GET['type'];

        $iniBlock = parse_ini_file(Yii::getPathOfAlias('common.blocks.' . $type) . DIRECTORY_SEPARATOR . 'info.ini');

        //import block type
        Yii::import("common.blocks.{$type}.{$iniBlock['class']}");

        $model = new Block();
        $model->type = $type;

        /**
         * create class from ini file
         */
        $blockModel = new $iniBlock['class']();

        $blockModel->beforeBlockSave();

        //check post and save data
        if ($this->_saveData($model, $blockModel) == 1) {
            //save successfully
            user()->setFlash('success', 'Create block successfully');

            $blockModel->afterBlockSave();

            //go to update
            $this->redirect(array('update', 'id' => $model->block_id));
        }

        $this->render('create', array(
            'model' => $model,
            'blockModel' => $blockModel,
            'blockInfo' => $iniBlock
        ));
    }

    /**
     * update block
     * @param int $id
     */
    public function actionUpdate($id) {
        $model = Block::model()->findByPk($id);

        if (!$model) {
            //404
            throw new CHttpException(404, 'Page was not exists');
        }
        $iniBlock = parse_ini_file(Yii::getPathOfAlias('common.blocks.' . $model->type) . DIRECTORY_SEPARATOR . 'info.ini');

        //import block type
        Yii::import("common.blocks.{$model->type}.{$iniBlock['class']}");

        $blockModel = new $iniBlock['class']();
        $blockModel->setParams(unserialize($model->params));

        $blockModel->beforeBlockSave();

        if ($this->_saveData($model, $blockModel) == 1) {

            $blockModel->afterBlockSave();

            //save successfully
            user()->setFlash('success', 'Update block successfully');
        }

        $this->render('create', array(
            'model' => $model,
            'blockModel' => $blockModel,
            'blockInfo' => $iniBlock
        ));
    }


    /**
     * create / update value from POST request
     * @param type $model
     * @param type $blockModel
     * @return int
     * 1 : save successfully
     * 2 : no post request, no action
     * 0 : validate error or save fail
     */
    private function _saveData($model, $blockModel) {
        //update value
        if (isset($_POST['Block'])) {
            //set block attributes
            $model->attributes = $_POST['Block'];
            $params = $blockModel->params();

            $blockParams = array();
            foreach ($params as $key => $param) {
                $blockParams[$key] = $blockModel->{$key} = isset($_POST['Block'][$key]) ? $_POST['Block'][$key] : NULL;
            }

            if ($model->validate()) {
                //validate block model
                if (!$blockModel->validate()) {
                    //set errors
                    foreach ($blockModel->errors as $key => $message) {
                        //bind error
                        $model->addError($key, $message);
                    }
                } else {
                    //save data
                    $model->params = serialize($blockParams);

                    if ($model->save()) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            } else {
                return 0;
            }
        } else {
            return 2;
        }
    }

    /**
     * get avaiable blocks
     * @return array blockid => blockname
     */
    private function _getAvaiableBlocks() {
        $blocks = app()->cache->get('avaiable-blocks');

        if ($blocks === false) {
            $blocks = array();

            $files = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator(Yii::getPathOfAlias('common.blocks'))
            );

            foreach ($files as $pathname => $fileinfo) {
                if ((!$fileinfo->isFile()))
                    continue;
                $type = substr($pathname, -3);
                if ($type == 'ini') {
                    $temp = parse_ini_file($pathname);

                    $blocks[$temp['id']] = $temp['name'];
                }
            }
            Yii::app()->cache->set('avaiable-blocks', $blocks, 7200);
        }


        return $blocks;
    }


    public function actionDelete($id){
        if(!r()->isPostRequest){
            throw new CHttpException(400, 'Request not invalid');
        }

        Block::model()->findByPk($id)->delete();
    }
}